package com.gitee.feizns.quickstart.web.domain.query;

import com.gitee.feizns.quickstart.domain.query.QueryAo;
import com.gitee.feizns.quickstart.jackson.Val;
import com.gitee.feizns.quickstart.web.WebUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 请求参数
 * @author feizns
 * @since 2025/6/14
 */
public class QueryParamsAo implements QueryAo {

    /**
     * 参数
     */
    private final Map<String, Object> params = requestParamsMap();

    @Override
    public Map<String, Object> params() {
        return params;
    }

    @Override
    public Val pluck(String key) {
        Val val = param(key);
        params.remove(key);
        return val;
    }

    /**
     * 针对java web请求参数的 Map<String, String[]> 转换为 Map<String, Object>
     * @param paramsMap 参数映射
     * @return {@link Map }<{@link String }, {@link Object }>
     */
    public static Map<String, Object> of(Map<String, ?> paramsMap) {
        Map<String, Object> result = new LinkedHashMap<>();
        for (Map.Entry<String, ?> entry : paramsMap.entrySet()) {
            //解析结果
            List<Object> va = Val.of(entry.getValue()).listValue().stream().flatMap(v -> {
                Val val = Val.of(v);
                if ( val.raw().isArray() )
                    return val.raw().listValue().stream().map(Val::of).map(QueryParamsAo::ifIsJsonObjectToMap);
                return Stream.of(ifIsJsonObjectToMap(val));
            }).collect(Collectors.toList());
            if ( va.isEmpty() )
                result.put(entry.getKey(), null);
            else if (va.size() == 1)
                result.put(entry.getKey(), va.get(0));
            else
                result.put(entry.getKey(), va);
        }
        return result;
    }

    /**
     * 如果是否是JSON 格式对象自地图
     * @param val 瓦尔
     * @return {@link Object }
     */
    public static Object ifIsJsonObjectToMap(Val val) {
        return val.raw().isObject() ? val.raw().mapValue() : val.objectValue();
    }

    /**
     * 要映射 JSON 值
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public static Map<String, Object> requestParamsMap() {
        return of(WebUtils.getReq().getParameterMap());
    }

}
